package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    //拦截器
    public JsonResult login(String username, String password, HttpSession session){//直接注入session对象
        try {
            Employee employee = employeeService.login(username,password);

            //把员工放到session中
            //session.setAttribute("USER_IN_SESSION",employee);
            //抽取上面的方法后,可以减少错误
            UserContext.setCurrentUser(employee);

            //判断是否是管理员,如果不是就执行里面的操作
            //如果这里没判断,必须在权限拦截器里(第5步)获取
            //不用每次判断的时候都去查数据库
            if (!employee.isAdmin()){
                //获取用户拥有的权限表达式列表
                List<String> expressions = permissionService.selectByEmpId(employee.getId());
                //存放到session中
                //EXPRESSION权限表达式的意思
                //抽取方法后不用这个
                //session.setAttribute("EXPRESSION_IN_SESSION",expressions);
                UserContext.setExpressions(expressions);
            }

            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }
    //注销
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();//销毁会话
        return "redirect:/login.html";
    }
}
